import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOperation, ApiTags, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { OssService } from './oss.service';
import * as path from 'path';

@Controller('oss')
@ApiTags('OSS模块')
export class OssController {
  constructor(private readonly ossService: OssService) { }

  @Post('upload')
  @ApiOperation({ summary: '上传文件' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    // 检查文件类型
    const allowedTypes = [
      '.mp3',
      '.wav',
      '.m4a',
      '.mp4',
      '.mov',
      '.png',
      '.jpg',
      '.jpeg',
      '.gif',
      '.bmp',
      '.webp',
    ];
    const ext = path.extname(file.originalname).toLowerCase();
    if (!allowedTypes.includes(ext)) {
      throw new BadRequestException('不支持的文件类型');
    }

    // 检查文件大小（100MB限制）
    const maxSize = 100 * 1024 * 1024; // 100MB in bytes
    if (file.size > maxSize) {
      throw new BadRequestException('文件大小不能超过100MB');
    }

    // 上传文件到OSS
    const url = await this.ossService.uploadFile(
      file.buffer,
      file.originalname,
    );

    return {
      success: true,
      url,
      filename: file.originalname,
    };
  }



}
